import {
	INodeExecutionData,
	type IExecuteFunctions,
	type INodeType,
	type INodeTypeDescription,
} from 'n8n-workflow';
import axios from 'axios';

const StatusOptions: any = [
	{
		value: 'DONE_SUCCESS',
		name: '完成',
	},
	{
		value: 'DOING',
		name: '进行中',
	},
	{
		value: 'DONE_FAIL',
		name: '失败',
	},
];

const WebHookNodes = new Set([
	'n8n-nodes-base.webhook',
	'n8n-nodes-exec-webhook.uncTrigger',
	'CUSTOM.uncTrigger',
]);

export class ReportNode implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'UNC日志上报',
		name: 'uncReport',
		icon: 'file:webhook.svg',
		group: ['transform'],
		version: 1,
		description: 'UNC日志上报',
		defaults: {
			name: 'UNC Report',
		},
		inputs: ['main'],
		outputs: ['main'],
		credentials: [
			{
				name: 'ReportNodeApi',
				required: true,
				displayName: 'UNC日志上报凭证',
			},
		],
		properties: [
			{
				displayName: '任务阶段',
				name: 'task_phase',
				type: 'options',
				default: 'NEW',
				placeholder: '请选择任务阶段',
				required: true,
				options: [
					{
						name: '创建',
						value: 'NEW',
					},
					{
						name: '采集',
						value: 'CRAWL',
					},
					{
						name: '解析',
						value: 'EXTRACT',
					}
				]
			},
			{
				displayName: '阶段状态',
				name: 'task_phase_status',
				type: 'options',
				default: '',
				placeholder: '请选择阶段状态',
				required: true,
				options: [
					...StatusOptions,
				]
			},
			{
				displayName: '任务状态',
				name: 'task_status',
				type: 'options',
				default: '',
				placeholder: '请输入任务状态',
				required: true,
				options: [
					{
						value: 'DONE_CRAWL',
						name: '已采集',
					},
					{
						value: 'DONE_EXTRACT',
						name: '已解析',
					},
					...StatusOptions,
				]
			},
		],
	};

	async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
		const items: any = [];
		let itemIndex = 0;
		try {
			const parentNodes = this.getParentNodes(this.getNode().name);
			const webhookNode = parentNodes?.find((node) => WebHookNodes.has(node.type));
			const workflowData = this.getWorkflowDataProxy(0);
			const firstJson: any = workflowData?.$items(webhookNode?.name)?.[0].json;
			// 从第一个节点获取task_id
			const task_id = firstJson?.task_id || firstJson?.body?.['task_id'] || firstJson?.headers?.['x-taskid'] || this.getExecutionId();
			const task_phase = this.getNodeParameter('task_phase', 0);
			const task_phase_status = this.getNodeParameter('task_phase_status', 0);
			const task_status = this.getNodeParameter('task_status', 0);
			const task_phase_data = this.getInputData(itemIndex)[0].json || {}; // 获取上一个节点的输入数据
			const credentials = await this.getCredentials('ReportNodeApi');
			const address = credentials?.address + '';
			const reportRet = await axios.post(address, {
				task_id,
				task_phase,
				task_phase_status,
				task_status,
				task_phase_data
			});
			// 上报成功
			items.push(...this.helpers.returnJsonArray({ task_id, ...task_phase_data, report: {...reportRet?.data} }));
		} catch (error) {
			// 上报接口不抛出异常
			items.push({ json: this.getInputData(itemIndex)[0].json, error, pairedItem: itemIndex });
		}
		return [items];
	}

}
